#!/usr/bin/env python
# encoding: utf-8
"""
user.py

Created by 刘 智勇 on 2011-06-25.
Copyright (c) 2011 __MyCompanyName__. All rights reserved.
"""
import re
from tornado.web import authenticated

from api import UserAPI
from common import BaseHandler
from tools import session, _unicode


class User(object):
    reg_keys = {'email':u'email', 'passwd':u'密码', 'repwd':u'密码确认'}
    def __init__(self, api=None):
        self._api = api if api else UserAPI()

    def whois(self, key, value):
        ret = self._api.one(**{key:value})
        if ret:
            self.info = ret
            self.uid = self.info['_id']
        else:
            self.uid = self.info = None

    def check_pwd(self, passwd):
        return (self.passwd is not None)and(self.passwd == passwd)
    
    def check_reg(self, **data):
        for i in data:
            v = data.get(i, [])
            v = [re.sub(r"[\x00-\x08\x0e-\x1f]", " ", x) for x in v]
            v = [_unicode(x) for x in v]
            v = [x.strip() for x in v]
            data[i] = v[-1]
        for k in self.reg_keys.keys():
            i = data.get(k, None)
            if i is None:return(False, u'请填写'+self.reg_keys[k])
        email = data.get('email', None)
        nick = data.get('nick', None)
        if self._api.is_email_exist(email):return(False, u'email已存在！')
        if (nick is not None) and (self._api.is_nick_exist(nick)):return(False, u'nick已存在!')
        if data.get('passwd', 'not') != data.get('repwd', 'equal'):return(False, u'密码不匹配！')
        ret_d = {}
        kwords_l = self._api.get_structure().keys()
        for i in data.keys():
            if i in kwords_l:
                ret_d[i] = data.pop(i)
        data.pop('repwd')
        ret_d.update(data)
        return (True, ret_d)

    def __getattr__(self, key):
        if hasattr(self, 'info') and self.info and (key in self.info):
            return self.info[key]
        else:
            return None

class LoginHandler(BaseHandler):
    @session
    def get(self):
        uid = self.SESSION['uid']
        n = self.get_secure_cookie("user")
        if n and uid:
            self.redirect('/')
        self.redirect('/')
    
    @session
    def post(self):
        email = self.get_argument('email', None)
        passwd = self.get_argument('passwd', None)
        if not email or not passwd:
            return self.redirect('/')
        u = User()
        u.whois('email', email)
        if u.check_pwd(passwd):
            n = u.nick.encode('utf-8') if u.nick else u.email
            self.set_secure_cookie("user", n, 1)
            self.SESSION['uid']=u._id
            self.redirect('/weibo')
        else:
            return self.redirect('/')

class LogoutHandler(BaseHandler):
    @authenticated
    @session
    def get(self):
        self.clear_cookie("user")
        try:del self.SESSION['uid']
        except:pass
        return self.redirect('/')

class RegisterHandler(BaseHandler):
    @session
    def post(self):
        u = User()
        cek_ret = u.check_reg(**self.request.arguments)
        if cek_ret[0]:
            info = cek_ret[1]
            email = info['email']
        else:
            return self.render('/')
        ret = u._api.create(**info)
        if ret[0]:
            u.whois('email', email)
            n = u.nick.encode('utf-8') if u.nick else u.email
            self.SESSION['uid']=u._id
            self.redirect('/weibo/')
        else:
            self.redirect('/')
    
